package com.example.mydy;

import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.mydy.adapter.UserRewardPrivilegeAdapter;
import com.example.mydy.model.UserRewardPrivilege;
import com.example.mydy.utils.MockDataManager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.Date;
import java.util.List;

/**
 * 特权用户管理界面
 */
public class PrivilegeUserManagementActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private UserRewardPrivilegeAdapter privilegeAdapter;
    private FloatingActionButton fabAddPrivilege;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_privilege_user_management);
        
        // 设置标题和返回按钮
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("特权用户管理");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        
        // 初始化控件
        recyclerView = findViewById(R.id.rv_privileges);
        fabAddPrivilege = findViewById(R.id.fab_add_privilege);
        
        // 设置RecyclerView
        setupRecyclerView();
        
        // 设置悬浮按钮点击事件
        fabAddPrivilege.setOnClickListener(v -> showAddPrivilegeDialog());
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 刷新数据
        refreshData();
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    private void setupRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        
        // 获取特权列表
        List<UserRewardPrivilege> privileges = MockDataManager.getUserRewardPrivileges();
        
        // 创建新的适配器
        privilegeAdapter = new UserRewardPrivilegeAdapter(this, privileges);
        privilegeAdapter.setOnPrivilegeActionListener(new UserRewardPrivilegeAdapter.OnPrivilegeActionListener() {
            @Override
            public void onClick(UserRewardPrivilege privilege) {
                // 查看特权详情
                showPrivilegeDetails(privilege);
            }
            
            @Override
            public void onEdit(UserRewardPrivilege privilege, int position) {
                // 编辑特权
                showPrivilegeEditDialog(privilege, position);
            }
            
            @Override
            public void onDelete(int id, int position) {
                // 删除特权
                deleteUserPrivilege(id, position);
            }
        });
        
        recyclerView.setAdapter(privilegeAdapter);
    }
    
    private void refreshData() {
        // 重新获取特权列表
        List<UserRewardPrivilege> privileges = MockDataManager.getUserRewardPrivileges();
        
        // 更新适配器数据
        if (privilegeAdapter != null) {
            privilegeAdapter.updateData(privileges);
        }
    }

    private void showPrivilegeDetails(UserRewardPrivilege privilege) {
        // 显示特权详情对话框
        new AlertDialog.Builder(this)
            .setTitle(privilege.getUsername() + " 的特权详情")
            .setMessage("一级分成: " + privilege.getLevel1Ratio() + "%\n" +
                     "二级分成: " + privilege.getLevel2Ratio() + "%\n" +
                     "三级分成: " + privilege.getLevel3Ratio() + "%\n" +
                     "邀请奖励: ¥" + privilege.getInviteReward() + "\n" +
                     "备注: " + privilege.getRemark())
            .setPositiveButton("确定", null)
            .show();
    }

    private void showPrivilegeEditDialog(UserRewardPrivilege privilege, int position) {
        // 显示编辑特权的对话框
        // 简化实现，实际应该使用自定义对话框
        Toast.makeText(this, "编辑用户 " + privilege.getUsername() + " 的特权", Toast.LENGTH_SHORT).show();
        
        // 这里应实现真实的编辑逻辑，现在仅做示例
        UserRewardPrivilege updatedPrivilege = new UserRewardPrivilege(
            privilege.getId(),
            privilege.getUsername(),
            privilege.getLevel1Ratio() + 1, // 增加一点分成比例
            privilege.getLevel2Ratio(),
            privilege.getLevel3Ratio(),
            privilege.getInviteReward(),
            privilege.getStartDate(),
            privilege.getEndDate(),
            privilege.getRemark() + " (已编辑)"
        );
        
        // 更新特权
        boolean success = MockDataManager.updateUserRewardPrivilege(updatedPrivilege);
        if (success) {
            // 更新列表
            privilegeAdapter.updatePrivilege(updatedPrivilege, position);
            Toast.makeText(this, "特权已更新", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "更新失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void deleteUserPrivilege(int id, int position) {
        new AlertDialog.Builder(this)
            .setTitle("删除特权")
            .setMessage("确定要删除该用户的特权设置吗？")
            .setPositiveButton("确定", (dialog, which) -> {
                boolean success = MockDataManager.deleteUserRewardPrivilege(id);
                if (success) {
                    privilegeAdapter.removePrivilege(position);
                    Toast.makeText(this, "特权设置已删除", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show();
                }
            })
            .setNegativeButton("取消", null)
            .show();
    }
    
    private void showAddPrivilegeDialog() {
        // 这里应该使用自定义对话框来添加特权
        // 简化起见，这里只创建一个默认的特权
        UserRewardPrivilege newPrivilege = new UserRewardPrivilege(
            0, // ID会由MockDataManager分配
            "new_user_" + System.currentTimeMillis() % 1000, // 生成一个随机用户名
            50.0, // 默认一级分成50%
            25.0, // 默认二级分成25%
            10.0, // 默认三级分成10%
            3.0,  // 默认邀请奖励3元
            new Date(), // 开始日期：当前日期
            null,       // 结束日期：永久有效
            "新添加的特权用户" // 备注
        );
        
        // 添加特权
        boolean success = MockDataManager.addUserRewardPrivilege(newPrivilege);
        if (success) {
            // 刷新列表
            refreshData();
            Toast.makeText(this, "特权已添加", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "添加特权失败", Toast.LENGTH_SHORT).show();
        }
    }
} 